﻿/* 
    Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
    Use of this sample source code is subject to the terms of the Microsoft license 
    agreement under which you licensed this sample source code and is provided AS-IS.
    If you did not accept the terms of the license agreement, you are not authorized 
    to use this sample source code.  For the terms of the license, please see the 
    license agreement between you and Microsoft.    
*/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Microsoft.Phone.BackgroundTransfer;

namespace BackgroundTransferServiceSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        IEnumerable<BackgroundTransferRequest> transferRequests;
        DispatcherTimer timer;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Initialize the DispatcherTimer that will update the
            // file transfer list, but don't start it yet.
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(300);
            timer.Tick += new EventHandler(timer_Tick);
        }



        private void ResetItemsList()
        {
            // Use Requests property to retrieve all of the transfer requests
            // stored for this application. 
            transferRequests = BackgroundTransferService.Requests;

            // If there are 1 or more transfers, hide the "no transfers"
            // TextBlock. IF there are zero transfers, show the TextBlock.
            if (transferRequests.Count<BackgroundTransferRequest>() > 0)
            {
                EmptyTextBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                EmptyTextBlock.Visibility = Visibility.Visible;
            }

            // Update the TransferListBox with the list of transfer requests.
            TransferListBox.ItemsSource = transferRequests;

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // When the page loads, refresh the list of file transfers.
            ResetItemsList();

            // Then start the timer to update the list periodically.
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            // The file transfer list should never be null here,
            // but check it to be safe.
            if (transferRequests == null)
            {
                timer.Stop();
                return;
            }

            // Loop through the transfer request list. 
            foreach (var transfer in transferRequests)
            {
                // If you find a transfer that is either transferring or waiting, 
                // Reset the transfers ListBox and exit the Tick method.
                if (transfer.TransferStatus == TransferStatus.Transferring || transfer.TransferStatus == TransferStatus.Waiting)
                {
                    ResetItemsList();
                    return;
                }
            }

            // If this line of code is reached, there are no transfers transferring
            // or waiting, so stop the timer.
            timer.Stop();
        }

        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // try to remove the transfer from the background transfer service.
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception )
            {
                // TBD. 
            }
        }

        private void RemoveButton_Click(object sender, EventArgs e)
        {
            // The ID for each transfer request is bound to the
            // Tag property of each Remove button.
            string transferID = ((Button)sender).Tag as string;

            // TODO - Perform actions on the transferred file, such
            // as copying it to another location.


            // Delete the transfer request
            RemoveTransferRequest(transferID);

            // Refresh the list of file transfers
            ResetItemsList();
        }

        private void RemoveAllCompletedButton_Click(object sender, EventArgs e)
        {
            // Loop through the list of transfer requests
            foreach (var transfer in BackgroundTransferService.Requests)
            {
                // Check to see if the transfer is completed.
                if (transfer.TransferStatus == TransferStatus.Completed)
                {
                    // TODO - Perform actions on the transferred file, such
                    // as copying it to another location.

                    // Delete the transfer request
                    RemoveTransferRequest(transfer.RequestId);
                }
            }

            // Refresh the list of file transfer requests.
            ResetItemsList();
        }

        private void AddBackgroundTransferButton_Click(object sender, EventArgs e)
        {
            // Navigate to the AddBackgroundTransfer page when the Add button
            // is tapped.
            NavigationService.Navigate(new Uri("/AddBackgroundTransfer.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {

        }

        private void ViewImagesButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/DisplayDownloadedFiles.xaml", UriKind.RelativeOrAbsolute));
        }
    }
}